﻿using MVP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinForms.Bku
{
    public partial class BkuEntryForm : Form, IBkuEntryFormView
    {
        private BkuEntryFormPresenter _presenter;
        public BkuEntryForm()
        {
            _presenter = new BkuEntryFormPresenter(this);
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

            penerimaanTextBox.KeyPress += RestrictOnKeyPress;
            pengeluaranTextBox.KeyPress += RestrictOnKeyPress;
            pajakYangDisetorTextBox.KeyPress += RestrictOnKeyPress;

            penerimaanTextBox.Leave += FormatCurrencyOnLeave;
            pengeluaranTextBox.Leave += FormatCurrencyOnLeave;
            pajakYangDisetorTextBox.Leave += FormatCurrencyOnLeave;
            pengeluaranTextBox.Leave += HitungPajak;

            penerimaanTextBox.Enter += UnformatCurencyOnEnter;
            pengeluaranTextBox.Enter += UnformatCurencyOnEnter;
            pajakYangDisetorTextBox.Enter += UnformatCurencyOnEnter;

            TogglePajakField(false);

            Initialize(null, new EventArgs());
        }

        #region IBkuEntryFormView

        public long Id
        { get; set; }

        public string Bulan
        { get; set; }

        public string Tahun
        { get; set; }

        public string Nomor
        {
            get
            {
                return nomorTextBox.Text;
            }
            set
            {
                nomorTextBox.Text = value;
            }
        }

        public DateTime Tanggal
        {
            get
            {
                return tanggalDateTimePicker.Value;
            }
            set
            {
                tanggalDateTimePicker.Value = value;
            }
        }

        public DataTable PosRekeningList
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                posRekeningComboBox.DataSource = value.DefaultView;
                posRekeningComboBox.DisplayMember = "uraian";
                posRekeningComboBox.ValueMember = "kode";
            }
        }

        public string KodeRekening
        {
            get
            {
                return posRekeningComboBox.SelectedValue.ToString();
            }
            set
            {
                posRekeningComboBox.SelectedValue = value;
            }
        }

        public string Uraian
        {
            get
            {
                return uraianTextBox.Text;
            }
            set
            {
                uraianTextBox.Text = value;
            }
        }

        public decimal Penerimaan
        {
            get
            {
                if (string.IsNullOrEmpty(penerimaanTextBox.Text))
                    return 0;
                return decimal.Parse(penerimaanTextBox.Text, NumberStyles.Currency | NumberStyles.Number);
            }
            set
            {
                penerimaanTextBox.Text = value.ToString("C2", CultureInfo.CreateSpecificCulture("id-ID"));
            }
        }

        public decimal Pengeluaran
        {
            get
            {
                if (string.IsNullOrEmpty(pengeluaranTextBox.Text))
                    return 0;
                return decimal.Parse(pengeluaranTextBox.Text, NumberStyles.Currency | NumberStyles.Number);
            }
            set
            {
                pengeluaranTextBox.Text = value.ToString("C2", CultureInfo.CreateSpecificCulture("id-ID"));
            }
        }

        public bool Pajak
        {
            get
            {
                return pajakCheckBox.Checked;
            }
            set
            {
                pajakCheckBox.Checked = value;
            }
        }

        public DataTable JenisPajakList
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                jenisPajakComboBox.DataSource = value.DefaultView;
                jenisPajakComboBox.DisplayMember = "uraian";
                jenisPajakComboBox.ValueMember = "kode";
            }
        }

        public string JenisPajak
        {
            get
            {
                return ((DataRowView)jenisPajakComboBox.SelectedItem)["uraian"].ToString();
            }
            set
            {
                jenisPajakComboBox.SelectedText = value;
            }
        }

        public string KodePajak
        {
            get
            {
                return jenisPajakComboBox.SelectedValue.ToString();
            }
            set
            {
                jenisPajakComboBox.SelectedValue = value;
            }
        }

        public decimal PajakYangDisetor
        {
            get
            {
                if (String.IsNullOrEmpty(pajakYangDisetorTextBox.Text))
                    return 0;
                return decimal.Parse(pajakYangDisetorTextBox.Text, NumberStyles.Currency | NumberStyles.Number);
            }
            set
            {
                pajakYangDisetorTextBox.Text = value.ToString("C2", CultureInfo.CreateSpecificCulture("id-ID"));
            }
        }

        public int SortOrder
        {
            get;
            set;
        }

        public IDictionary<string, object> FieldValues
        {
            get
            {
                IDictionary<string, object> fieldValues = new Dictionary<string, object>();
                fieldValues.Add("id", Id);
                fieldValues.Add("bulan", Bulan);
                fieldValues.Add("tahun", Tahun);
                fieldValues.Add("nomor", Nomor);
                fieldValues.Add("tanggal", Tanggal);
                fieldValues.Add("pos_rekening", KodeRekening);
                fieldValues.Add("uraian", Uraian);
                fieldValues.Add("penerimaan", Penerimaan);
                fieldValues.Add("pengeluaran", Pengeluaran);
                fieldValues.Add("pajak", Pajak);
                fieldValues.Add("jenis_pajak", JenisPajak);
                fieldValues.Add("kode_pajak", KodePajak);
                fieldValues.Add("pajak_yang_disetor", PajakYangDisetor);
                fieldValues.Add("sort_order", SortOrder);
                return fieldValues;
            }
            set { }
        }

        public event EventHandler Initialize;

        #endregion IBkuEntryFormView


        #region EventHandler

        private void okButton_Click(object sender, EventArgs e)
        {
            if (IsValid())
            {
                //this.Close();
                //this.Dispose();
            }
        }

        private void posRekeningComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            uraianTextBox.Text = ((DataRowView)posRekeningComboBox.SelectedItem)["uraian"].ToString();
        }

        private void pajakCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            TogglePajakField(((CheckBox)sender).Checked);
        }

        private void jenisPajakComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int kode = Convert.ToInt32(jenisPajakComboBox.SelectedValue);
            pajakYangDisetorTextBox.ReadOnly = kode != (int)Common.JenisPajak.PajakLainnya;
            HitungPajak(null, null);
        }

        #endregion EventHandler

        #region CurrencyFormat

        private void RestrictOnKeyPress(object sender, KeyPressEventArgs e)
        {
            // only allow one decimal point
            if (e.KeyChar == ',')
            {
                if ((sender as TextBox).Text.IndexOf(',') > -1)
                    e.Handled = true;
            }
            else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
        }

        private void FormatCurrencyOnLeave(object sender, EventArgs e)
        {
            TextBox txtbox = ((TextBox)sender);
            if (string.IsNullOrEmpty(txtbox.Text) || txtbox.ReadOnly)
                return;
            decimal value = 0;
            try
            {
                value = Convert.ToDecimal(txtbox.Text);
            }
            catch (Exception)
            {
                value = Convert.ToDecimal(textBoxValueHistory);
            }
            txtbox.Text = value.ToString("C2", CultureInfo.CreateSpecificCulture("id-ID"));
        }

        private void UnformatCurencyOnEnter(object sender, EventArgs e)
        {
            TextBox txtbox = ((TextBox)sender);
            if (string.IsNullOrEmpty(txtbox.Text) || txtbox.ReadOnly)
                return;
            decimal value = decimal.Parse(txtbox.Text, NumberStyles.Currency | NumberStyles.Number);
            txtbox.Text = Convert.ToString(value);

            textBoxValueHistory = txtbox.Text;
        }

        #endregion CurrencyFormat

        #region Pajak

        private void TogglePajakField(bool enabled)
        {
            jenisPajakComboBox.Enabled = enabled;
            pajakYangDisetorTextBox.Enabled = enabled;
            HitungPajak(null, null);
        }

        private void HitungPajak(object sender, EventArgs e)
        {
            int kode = Convert.ToInt32(jenisPajakComboBox.SelectedValue);
            float percentage = 0;
            if (kode == (int)Common.JenisPajak.PPh21) percentage = .05F;
            else if (kode == (int)Common.JenisPajak.PPh21PPn) percentage = .015F;
            PajakYangDisetor = Convert.ToDecimal(percentage * Convert.ToInt64(Pengeluaran));
        }

        #endregion Pajak

        private bool IsValid()
        {
            return true;
        }

        private string textBoxValueHistory = null;

    }
}
